package yunwo.cn.yzstation.presenter;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;
import android.util.SparseArray;
import android.widget.Toast;

import java.io.File;

import yunwo.cn.yzstation.R;
import yunwo.cn.yzstation.api.ISettingModel;
import yunwo.cn.yzstation.api.ISettingView;
import yunwo.cn.yzstation.base.BasePresenter;
import yunwo.cn.yzstation.bean.Bean;
import yunwo.cn.yzstation.config.IntentTag;
import yunwo.cn.yzstation.model.SettingActivityModel;
import yunwo.cn.yzstation.utils.FileUtil;
import yunwo.cn.yzstation.utils.StringUtil;
import yunwo.cn.yzstation.utils.UIUtils;
import yunwo.cn.yzstation.view.activity.CutPicActivity;
import yunwo.cn.yzstation.view.activity.MainActivity;
import yunwo.cn.yzstation.view.activity.SettingActivity;

/**
 * Created by lao on 2017/9/7.
 */

public class SettingActivityPersenter extends BasePresenter<ISettingView> implements ISettingModel {
    private final SettingActivity activity;
    private final ISettingView mImainView;
    private SparseArray<String> capturePicFilePathMap;
    private SparseArray<String> selectPicFilePathMap;
    private final SharedPreferences mSaveiconSP;
    private final SharedPreferences.Editor mIconEdit;
    private final SettingActivityModel mMainActivityModel;

    public SettingActivityPersenter(SettingActivity activity, ISettingView imainView) {
        attachView(imainView);
        this.activity = activity;
        this.mImainView = imainView;
        mMainActivityModel = new SettingActivityModel(activity,this);
        capturePicFilePathMap = new SparseArray<String>();
        selectPicFilePathMap = new SparseArray<String>();
        mSaveiconSP = activity.getSharedPreferences("information", Context.MODE_PRIVATE);
        mIconEdit = mSaveiconSP.edit();
    }

    public void selectImage(int selectPhotoId) {
        Intent intent = new Intent();
        intent.setAction(IntentTag.SELECT_PHOTO_ACTION);
        intent.setType(IntentTag.SELECT_PHOTO_TYPE);
        mPresenterView.startMyActivityForResult(intent, selectPhotoId);
    }



    /**
     * 从照相机拍摄的图片,然后跳转到截取图片界面
     *
     * @param capturePhoto
     * @param cutPhoto
     */
    public void setCapturePhoto(int capturePhoto, int cutPhoto) {
        String capturePicFilePath = capturePicFilePathMap.get(capturePhoto);
        if (!StringUtil.isEmpty(capturePicFilePath) && new File(capturePicFilePath).length() != 0) {
//            CutPicActivity.bitmap = null;
            Intent intent = new Intent(activity, CutPicActivity.class);
            Log.d("TAG", "capturePicFilePath" + capturePicFilePath);
            intent.putExtra(IntentTag.CUT_PICTURE_PATH, capturePicFilePath);
            intent.putExtra(IntentTag.IS_CAPTURE, true);
            mPresenterView.startMyActivityForResult(intent, cutPhoto);
        }
    }



    /**
     * 从图库选择的图片,然后跳转到截取图片界面
     *
     * @param data
     * @param cutSelectPhoto
     */
    public void setSelectPhoto(Intent data, int cutSelectPhoto) {
        if (data != null) {
            Uri uri = data.getData();
            if (uri != null) {
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = activity.getContentResolver().query(uri, filePathColumn, null, null, null);
                if (cursor != null) {
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    if (!StringUtil.isEmpty(picturePath)) {
                        cursor.close();
                        Intent intent = new Intent(activity, CutPicActivity.class);
                        intent.putExtra(IntentTag.CUT_PICTURE_PATH, picturePath);
                        intent.putExtra(IntentTag.IS_CAPTURE, false);
                        mPresenterView.startMyActivityForResult(intent, cutSelectPhoto);
                    } else {

                    }
                } else {
                    setXiaoPhoto(data, cutSelectPhoto);
//                    UIUtils.showToastSafe(R.string.use_capture);
                }
            }
        }
    }
    private void setXiaoPhoto(Intent data, int cutSelectPhoto) {
        if (data == null) {
            return;
        }
//        Uri uri = data.getData();
        Uri uri = geturi(data);//解决方案
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = activity.managedQuery(uri, proj, null, null, null);
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String path = cursor.getString(column_index);// 图片在的路径
//            Intent intent3 = new Intent(this, SYClipActivity.class);
//            intent3.putExtra("path", path);
//            startActivityForResult(intent3, IMAGE_COMPLETE);
//            cursor.close();
            Intent intent = new Intent(activity, CutPicActivity.class);
            intent.putExtra(IntentTag.CUT_PICTURE_PATH, path);
            intent.putExtra(IntentTag.IS_CAPTURE, false);
            mPresenterView.startMyActivityForResult(intent, cutSelectPhoto);
        } else {
            UIUtils.showToastSafe("请使用拍照功能上传图片");
        }

    }

    /**
     * 拍照
     *
     * @param photoId
     */
    public void capturePicture(int photoId) {
        Log.e("1111111111", "222222222");
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        String iconDir = FileUtil.getIconDir();
        String capturePicFilePath = iconDir + System.currentTimeMillis() + ".jpg";
        capturePicFilePathMap.put(photoId, capturePicFilePath);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(capturePicFilePath)));
        mPresenterView.startMyActivityForResult(intent, photoId);
        Log.e("1111111111", "333333333333333");
    }
    /**
     * 解决小米手机上获取图片路径为null的情况
     *
     * @param intent
     * @return
     */
    public Uri geturi(Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = activity.getContentResolver();
                StringBuffer buff = new StringBuffer();
                buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
                        .append("'" + path + "'").append(")");
                Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID},
                        buff.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }
    public void setCutImageView(String filePath, int capturePhoto, int selectPhoto, boolean isCapture, final String userName) {
        if (!StringUtil.isEmpty(filePath)) {
            if (isCapture) {
                // 将bitmap写入文件
                selectPicFilePathMap.put(selectPhoto, filePath);
                capturePicFilePathMap.put(capturePhoto, "");
            } else {
                capturePicFilePathMap.put(capturePhoto, filePath);
                selectPicFilePathMap.put(selectPhoto, "");
            }
//            mPresenterView.showIconImage(UIUtils.getString(R.string.file_header) + filePath);
            //  // TODO: 2017/9/9     注释了上传图片都服务器的代码    this.269   indexpresenter 192


//            mPresenterView.loadPhotoProgressDialog();
            mMainActivityModel.postData(new File(filePath), capturePhoto);
        }
    }
    public void loadInfos() {
        setPersonIcon();
       /* ApplicationInfo info = ApplicationInfo.getInstance();
        setNickName(info.getUserName());
        String userType = info.getUserType();
        LogUtil.d(TAG, "userType:" + userType);
        if (MyConstants.USER_TYPE_WORKER.equals(userType)) {
            setIdentifyPhoto();
        }*/
    }
    /**
     * 设置用户图像
     */
    public void setPersonIcon() {
        String path = "";
        if (!StringUtil.isEmpty(mSaveiconSP.getString("LocalPic", ""))) {
            path = mSaveiconSP.getString("LocalPic", "");
        } else if (!StringUtil.isEmpty(mSaveiconSP.getString("NetPic", ""))) {
            path = mSaveiconSP.getString("NetPic", "");
        }
        if (!StringUtil.isEmpty(path)) {
            mPresenterView.showIconImage(path);
        }
    /*    String path = "";
        if (!StringUtil.isEmpty(ApplicationInfo.getInstance().getUserPicture())) {
            path = ApplicationInfo.getInstance().getUserPicture();
        } else if (!StringUtil.isEmpty(ApplicationInfo.getInstance().getUserFilePath())) {
            path = ApplicationInfo.getInstance().getUserFilePath();
        }
        LogUtil.d(TAG, "setPersonIcon path: " + path);


        //保存本地
        path = mSaveiconSP.getString("saveicon", "");

        if (!StringUtil.isEmpty(path))
            mPresenterView.showIconImage(path);*/
    }

    @Override
    public void UploadSuccess(Bean bean,File file) {
        Toast.makeText(activity, "上传成功", Toast.LENGTH_SHORT).show();
        mPresenterView.showIconImage(UIUtils.getString(R.string.file_header) + file.getAbsolutePath());
        mIconEdit.putString("LocalPic",UIUtils.getString(R.string.file_header) + file.getAbsolutePath());
        mIconEdit.putString("NetPic", bean.getData());
        mIconEdit.commit();


    }

    @Override
    public void UpDateNickSuccess(String nick) {
        mImainView.UpDateNickSuccess(nick);
        mIconEdit.putString("username", nick);
        mIconEdit.commit();
    }

    @Override
    public void LogoutSuccess() {

        mImainView.LogoutSuccess();
    }

    @Override
    public void UpDateNickfailure() {
        mImainView.UpDateNickfailure();
    }

    public void upDateNick(String nick) {
        mMainActivityModel.upDateNick(nick);
    }

    public void Logout() {

        mMainActivityModel.Logout();
    }
}
